package com.ruoyi.project.system.controller;

import java.io.File;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysPostService;
import com.ruoyi.project.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.domain.THrEmpInfo;
import com.ruoyi.project.system.service.ITHrEmpInfoService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * 人力资源管理Controller
 *
 * @author ruoyi
 * @date 2020-04-04
 */
@RestController
@RequestMapping("/system/INFO")
public class THrEmpInfoController extends BaseController
{
    @Autowired
    private ITHrEmpInfoService tHrEmpInfoService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Value("${ruoyi.profile}")
    private String filePath;

    /**
     * 查询人力资源管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:INFO:list')")
    @GetMapping("/list")
    public TableDataInfo list(THrEmpInfo tHrEmpInfo)
    {
        startPage();
        List<THrEmpInfo> list = tHrEmpInfoService.selectTHrEmpInfoList(tHrEmpInfo);
        return getDataTable(list);
    }

    /**
     * 导出人力资源管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:INFO:export')")
    @Log(title = "人力资源管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(THrEmpInfo tHrEmpInfo)
    {
        List<THrEmpInfo> list = tHrEmpInfoService.selectTHrEmpInfoList(tHrEmpInfo);
        ExcelUtil<THrEmpInfo> util = new ExcelUtil<THrEmpInfo>(THrEmpInfo.class);
        return util.exportExcel(list, "INFO");
    }

    /**
     * 获取人力资源管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:INFO:query')")
    @GetMapping(value = "/{pid}")
    public AjaxResult getInfo(@PathVariable("pid") Long pid)
    {
        return AjaxResult.success(tHrEmpInfoService.selectTHrEmpInfoById(pid));
    }

    /**
     * 新增人力资源管理
     */
    @PreAuthorize("@ss.hasPermi('system:INFO:add')")
    @Log(title = "人力资源管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody THrEmpInfo tHrEmpInfo)
    {
        return toAjax(tHrEmpInfoService.insertTHrEmpInfo(tHrEmpInfo));
    }

    /**
     * 修改人力资源管理
     */
    @PreAuthorize("@ss.hasPermi('system:INFO:edit')")
    @Log(title = "人力资源管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody THrEmpInfo tHrEmpInfo)
    {
        return toAjax(tHrEmpInfoService.updateTHrEmpInfo(tHrEmpInfo));
    }

    /**
     * 删除人力资源管理
     */
    @PreAuthorize("@ss.hasPermi('system:INFO:remove')")
    @Log(title = "人力资源管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{pids}")
    public AjaxResult remove(@PathVariable Long[] pids)
    {
        return toAjax(tHrEmpInfoService.deleteTHrEmpInfoByIds(pids));
    }

    @Log(title = "入职流程导入", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<THrEmpInfo> util = new ExcelUtil<THrEmpInfo>(THrEmpInfo.class);
        List<THrEmpInfo> list = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = tHrEmpInfoService.importUser(list, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<THrEmpInfo> util = new ExcelUtil<THrEmpInfo>(THrEmpInfo.class);
        return util.importTemplateExcel("入职申请模板");
    }

    /**
     * 修改人力资源管理
     */
//    @PreAuthorize("@ss.hasPermi('system:INFO:edit')")
    @Log(title = "人力资源管理sp", businessType = BusinessType.UPDATE)
    @PostMapping("/updateSP")
    public AjaxResult sp(MultipartFile file, String isAgree,String reason,String ids)
    {

        String fileName  = file.getOriginalFilename();
        String fileNameNew = fileName.substring(0, fileName.lastIndexOf("."))
                +System.currentTimeMillis()+"."
                + fileName.substring(fileName.lastIndexOf("."));
        toSaveFile(file,fileNameNew);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String[] pids = ids.split("-");
        List<Long> longs = getPids(pids);
        String empStatus = "2";
        if(isAgree.equals("0")){
            empStatus ="1";
        }
        Map<String,Object> map = new HashMap<>();
        map.put("hrStaffId",operName);
        map.put("isAgree",isAgree);
        map.put("isPass",reason);
        map.put("organizeFilePath",fileNameNew);
        map.put("list",longs);
        map.put("empStatus",empStatus);
        return toAjax(tHrEmpInfoService.updateTHrEmpInfoSP(map));
    }

    private List<Long> getPids(String[] ids){
        List<Long> list = new ArrayList<>();
        for (int i = 0; i <ids.length ; i++) {
            list.add(Long.valueOf(ids[i]));
        }
        return list;
    }

    private void toSaveFile(MultipartFile file,String fileName){
        if (!file.isEmpty()) {
            try {
                // getOriginalFilename()是包含源文件后缀的全名
                String filePathNew = filePath+"/"+fileName;
                System.out.println(filePathNew);
                File saveDir = new File(filePathNew);
                if (!saveDir.getParentFile().exists())
                    saveDir.getParentFile().mkdirs();
                file.transferTo(saveDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  审核节点 查询人力资源管理列表
     */
    @GetMapping("/listSP")
    public TableDataInfo listSP(THrEmpInfo tHrEmpInfo)
    {
        startPage();
        List<THrEmpInfo> list = tHrEmpInfoService.selectTHrEmpInfoListSp(tHrEmpInfo);
        return getDataTable(list);
    }

}
